import { ref, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useLocalStorage } from '@vueuse/core';

import { toast } from '@/utils/toastHelper';

export function useMemoEdit() {
  const route = useRoute();
  const router = useRouter();

  const id = route.params.id;
  const memoList = useLocalStorage('memo-list', []);

  const currentMemoItem = computed(() => {
    return memoList.value.find((item) => Number(item.id) === Number(id));
  });

  const title = ref(currentMemoItem.value.title);
  const body = ref(currentMemoItem.value.body);

  function updateMemo() {
    memoList.value = memoList.value.map((memoItem) => {
      if (Number(memoItem.id) === Number(id)) {
        return {
          ...memoItem,
          title: title.value,
          body: body.value,
        };
      }

      return memoItem;
    });

    toast('成功更新');

    router.push('/memo');
  }

  return {
    title,
    body,
    updateMemo,
  };
}
